<?php
include_once "wxBizMsgCrypt.php";
//file_put_contents('./log/2.txt', json_encode($_GET), FILE_APPEND);
 
// 第三方发送消息给公众平台
$encodingAesKey = "kAY0ar3xv6RAX8EdgUIaSBBDLEuKjAYeVi6WweAxWh4";
$token = "7a616f4a0af798d6011494843e2fc78f";
$appId = "wx82aa345f1fb8714b";
$timeStamp  = empty($_GET['timestamp']) ? "" : trim($_GET['timestamp']) ;
$nonce      = empty($_GET['nonce']) ? "" : trim($_GET['nonce']) ;
$msg_sign   = empty($_GET['msg_signature']) ? ""    : trim($_GET['msg_signature']) ;

$encryptMsg = file_get_contents('php://input');
$pc = new WXBizMsgCrypt($token, $encodingAesKey, $appId);
 
$xml_tree = new DOMDocument();
$xml_tree->loadXML($encryptMsg);
$array_e = $xml_tree->getElementsByTagName('Encrypt');
$encrypt = $array_e->item(0)->nodeValue;
$format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
$from_xml = sprintf($format, $encrypt);

 
$msg = '';
$errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
$component_verify_ticket ="";
logResult(1,$errCode);
if ($errCode == 0) {
    $xml = new DOMDocument();
    $xml->loadXML($msg);
    
    logResult(3,$msg);
    
    $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
    $component_verify_ticket = $array_e->item(0)->nodeValue;
    file_put_contents('./log/component_verify_ticket.json', $component_verify_ticket);
    echo 'success';
}else {
    logResult(2,'解密后失败：'.$errCode);
    print($errCode . "\n");
}





function logResult($file,$data){
    file_put_contents('./log/'.$file.'.txt', $data,FILE_APPEND);
}













exit;

$text = "<xml><ToUserName><![CDATA[oia2Tj我是中文jewbmiOUlr6X-1crbLOvLw]]></ToUserName><FromUserName><![CDATA[gh_7f083739789a]]></FromUserName><CreateTime>1407743423</CreateTime><MsgType><![CDATA[video]]></MsgType><Video><MediaId><![CDATA[eYJ1MbwPRJtOvIEabaxHs7TX2D-HV71s79GUxqdUkjm6Gs2Ed1KF3ulAOA9H1xG0]]></MediaId><Title><![CDATA[testCallBackReplyVideo]]></Title><Description><![CDATA[testCallBackReplyVideo]]></Description></Video></xml>";






$pc = new WXBizMsgCrypt($token, $encodingAesKey, $appId);
$encryptMsg = '';
$errCode = $pc->encryptMsg($text, $timeStamp, $nonce, $encryptMsg);
if ($errCode == 0) {
	print("加密后: " . $encryptMsg . "\n");
} else {
	print($errCode . "\n");
}

$xml_tree = new DOMDocument();
$xml_tree->loadXML($encryptMsg);
$array_e = $xml_tree->getElementsByTagName('Encrypt');
$array_s = $xml_tree->getElementsByTagName('MsgSignature');
$encrypt = $array_e->item(0)->nodeValue;
$msg_sign = $array_s->item(0)->nodeValue;

$format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
$from_xml = sprintf($format, $encrypt);

// 第三方收到公众号平台发送的消息
$msg = '';
$errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
if ($errCode == 0) {
	print("解密后: " . $msg . "\n");
	
	//file_put_contents('./log/1.txt', $msg, FILE_APPEND);
	
} else {
    //file_put_contents('./log/1.txt', $errCode, FILE_APPEND);
	print($errCode . "\n");
}
